package com.creative.user.service.Impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.creative.config.AppConfig;
import com.creative.constant.Constants;
import com.creative.core.page.TableDataInfo;
import com.creative.core.uitls.Uidutil;
import com.creative.user.domain.UserInfo;
import com.creative.user.domain.vo.UserInfoVo;
import com.creative.user.mapper.UserInfoMapper;
import com.creative.user.service.UserInfoService;
import com.creative.utils.RedisUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Objects;

/**
 * @author Ling
 * @description 用户信息表
 * @date 2024-11-12
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    public static final Log logger = LogFactory.get();
    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private RedisUtils RedisUtils;

    @Resource
    private AppConfig appConfig;


    @Override
    public Integer insert(UserInfo userInfo) {
        //      随机生成uid (15位以内)
        String id = Uidutil.generateUid(10);
        // 设置主键
        userInfo.setUserId(id);
        userInfo.setCreateTime(DateUtil.date());
        return userInfoMapper.insert(userInfo);
    }

    @Override
    public Integer delete(String userId) {
        return userInfoMapper.delete(userId);
    }

    @Override
    public Integer deleteBatch(String[] ids) {
        return userInfoMapper.deleteBatch(ids);
    }

    @Override
    public Integer update(UserInfo userInfo) {
        return userInfoMapper.update(userInfo);
    }

    @Override
    public UserInfo selectById(String userId) {
        return userInfoMapper.selectById(userId);
    }

    @Override
    public TableDataInfo selectUserInfoList(UserInfo userInfo) {
        PageHelper.startPage(userInfo.getPageNum(), userInfo.getPageSize());
        List<UserInfo> list = userInfoMapper.selectUserInfoList(userInfo);
        Page<UserInfo> page = (Page<UserInfo>) list;
//    构建返回结果
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        //        转换为vo
        List<UserInfoVo> userInfoVo = BeanUtil.copyToList(page.getResult(), UserInfoVo.class);
        tableDataInfo.setRows(userInfoVo);
        tableDataInfo.setTotal(page.getTotal());
        return tableDataInfo;
    }

    @Override
    public List<UserInfo> exportBatch(String[] ids) {
        return userInfoMapper.exportBatch(ids);
    }

    @Override
    public UserInfo selectByNameAndPassword(String nickName, String password) {

        return userInfoMapper.selectByNameAndPassword(nickName, password);
    }

    @Override
    public UserInfo selectByEmail(String email) {
        return userInfoMapper.selectByEmail(email);
    }

    @Override
    public Integer updateAvatar(String avatar, String name) {
//        获取当前用户id
        SaSession session = StpUtil.getSession();
        String userId = (String) session.getLoginId();
        logger.info("当前用户为：" + userId);
//      判断文件类型
        String filetype = null;
        String[] strings = StrUtil.splitToArray(avatar, ",");
        if (strings[0].contains("png")) {
            filetype = "png";
        }
        if (strings[0].contains("jpg")) {
            filetype = "jpg";
        }
        if (strings[0].contains("jpeg")) {
            filetype = "jepg";
        }
//        根据前端传递的数据，来灵活改变
        avatar = strings[1];

        try {
            if (avatar != null) {
//                将base64转换为bytes数组
                byte[] byteArray = Base64.decode(avatar);
//                文件保存目录
                String filePath = appConfig.getFileSavePath() + Constants.FILE_SAVE_PATH + Constants.FILE_FOLDER_AVATAR_NAME;
//            创建文件
                if (Objects.equals(filetype, "jepg")) {
                    filetype = "jpg";
                }
                String fileName = filePath + userId + "." + filetype;
//                删掉旧数据

//                将文件路径存入数据库
                UserInfo userInfo = userInfoMapper.selectById(userId);
                userInfo.setAvatar(fileName);
                this.update(userInfo);
//                logger.info("旧头像为：" + userInfo);

                File file = new File(fileName);
//                FileOutputStream fos = new FileOutputStream(fileName);

//                如果文件已存在，则替换此文件
                if (file.exists()) {
//                    覆盖文件
                    FileUtil.writeBytes(byteArray, file);
                    logger.info("头像保存成功！");
                } else {
                    //                如果文件不存在
//                    生成新文件
                    FileUtil.touch(file);
                    FileUtil.writeBytes(byteArray, file);
                    logger.info("头像创建成功！");
                }
                return 1;
            }
        } catch (Exception e) {
            logger.error("修改头像失败！" + e.getMessage());
            throw new RuntimeException("修改头像失败！", e);
        }
        return 0;
    }

    @Override
    public Integer updatePassword(String password, String userId) {
        return userInfoMapper.updatePassword(password, userId);
    }


    @Override
    public UserInfo selectByWXOpenId(String wxOpenId) {
        return userInfoMapper.selectByWXOpenId(wxOpenId);
    }

    @Override
    public Long calculateUser() {
        return userInfoMapper.calculateUser();
    }


}